//
//  EmoticonViewController.swift
//  表情键盘布局
//
//  Created by x on 2017/7/10.
//  Copyright © 2017年 HLB. All rights reserved.
//
import UIKit

/// 保存cell重用的标示
private let EmoticonCellReuseIdentifier = "EmoticonCellReuseIdentifier"

class EmoticonViewController: UIViewController {
    
    
    /// 使用闭包来传至(保存表情的闭包)
    var emoticonDidSelectCallBack:(_ emoticon: Emoticons)->()
    
    init(callBack:@escaping (_ emoticon: Emoticons)->()) {
        //swift中重写控制器的init方法 要先初始化本控制器 在调用父类控制器的方法
        self.emoticonDidSelectCallBack = callBack
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.red
        //初始化UI
        setupUI()
        
        //print(EmoticonPackge.loadPackages())
    }
    
    /// 初始化UI
    func setupUI() -> Void {
        //1.添加子控件
        view.addSubview(emoticonCollectionView)
        view.addSubview(emoticonTolBar)
        emoticonCollectionView.translatesAutoresizingMaskIntoConstraints = false
        emoticonTolBar.translatesAutoresizingMaskIntoConstraints = false
        
        //2.布局子控件
        //注意:如果自己想要封装一个框架,最好不要使用别的框架
        var cons = [NSLayoutConstraint]()
        let dic = ["emoticonCollectionView":emoticonCollectionView,"emoticonTolBar":emoticonTolBar] as [String : Any]
        
        //第一个参数是VisualFormat约束的字符串  最后一个参数是告诉约束是对那个视图 字典中用的到的就取,用不到的就不取 H代表水平方向
        //设置emoticonCollectionView距离左边和右边的距离为0
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[emoticonCollectionView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        //设置emoticonTolBar距离左边部和右边的距离为0
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[emoticonTolBar]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        //V代表垂直方向 "V:|-0-[emoticonCollectionView]-[emoticonTolBar(44)]-0-|"  距离emoticonCollectionView底部为0   emoticonTolBar(44) 高度为44
        //设置emoticonCollectionView顶部距离为0底部距离emoticonTolBar顶部为0 并且emoticonTolBar的高度为44
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[emoticonCollectionView]-[emoticonTolBar(44)]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: dic)
        
        view.addConstraints(cons)
        
    }
    /// 表情选择器
    ///
    /// - Parameter item: <#item description#>
    func itemClick(item: UIBarButtonItem) -> Void {
        //collectionView滚动到指定的indePath地方 向左边滑动
        emoticonCollectionView.scrollToItem(at: IndexPath.init(item: 0, section: item.tag), at: UICollectionViewScrollPosition.left, animated: true)
    }
    
    //MARK: -- 懒加载
    
    /// 表情collectionView
    private lazy var emoticonCollectionView:UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmoticonLayout())
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCellReuseIdentifier)
        
        return collectionView
    }()
    
    /// 保存item的tag
    var itemTag:NSInteger = 0
    
    /// 表情选择tolBar
    private lazy var emoticonTolBar: UIToolbar = {
        let tolBar = UIToolbar()
        tolBar.tintColor = UIColor.darkGray
        var items = [UIBarButtonItem]()
        let titles = ["最近","默认","emoji","浪小花"]
        var itemTag = 0
        for title in titles {
            
            let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.plain, target: self, action: #selector(itemClick(item:)))
            item.tag = itemTag
            itemTag += 1
            items.append(item)
            
            //给tolBar添加弹簧
            let fileSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            items.append(fileSpace)
        }
        //移除最后一个弹簧
        items.removeLast()
        tolBar.items = items
        return tolBar
    }()
    
    /// 表情显示数据源
    fileprivate lazy var packages:[EmoticonPackge] = EmoticonPackge.packgeList
    
}

extension EmoticonViewController: UICollectionViewDelegate,UICollectionViewDataSource {

    //有几个分区
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    //告诉系统有多少行
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    //告诉系统每行显示什么内容
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCellReuseIdentifier, for: indexPath) as! EmoticonCollectionViewCell
        cell.backgroundColor = (indexPath.item % 2) == 0 ? UIColor.red : UIColor.green
        cell.emoticonsModel = packages[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }
    
    //选中某一个cell时调用
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let model = packages[indexPath.section].emoticons![indexPath.item]
        model.counts += 1
        
        //1.处理最近表情,将选中的表情都添加到最近表情中
        packages[0].appendEmoticons(emoticon: model)
        //刷新最近的的表情排序
        collectionView.reloadSections(IndexSet(integer: 0))
        
        //2.回调通知使用者选中了那个表情
        self.emoticonDidSelectCallBack(model)
    }
}

class EmoticonLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        //1.设置一些布局属性
        let with = collectionView!.bounds.width / 7
        itemSize = CGSize(width: with, height: with)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.horizontal
        
        //2.设置collectinView的一些属性
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
        
        // 注意:最好不要乘以0.5, 因为CGFloat不准确, 所以如果乘以0.5在iPhone4/4身上会有问题
        let y = (collectionView!.bounds.height - with*3) * 0.49
        collectionView?.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        
    }
}

class EmoticonCollectionViewCell: UICollectionViewCell {
    
    var emoticonsModel:Emoticons?{
        didSet{
            //1.判断是不是图片表情
            if emoticonsModel!.chs != nil {
                //代表是图片表情
                emoticonBtn.setImage(UIImage.init(contentsOfFile: (emoticonsModel?.emoticonPath)!), for: UIControlState.normal)
            }else {
                emoticonBtn.setImage(nil, for: UIControlState.normal)
            }
            //2.设置emoji表情
            //代表十六进制字符串的表情
            emoticonBtn.setTitle(emoticonsModel!.emoticonStr ?? "", for: UIControlState.normal)
            
            //判断是否是删除按钮
            if (emoticonsModel?.isRemoveBtn)! {
                emoticonBtn.setImage(UIImage.init(named: "compose_emotion_delete"), for: UIControlState.normal)
                emoticonBtn.setImage(UIImage.init(named: "compose_emotion_delete_highlighted"), for: UIControlState.highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //1.添加子控件
        contentView.addSubview(emoticonBtn)
        
        //2.布局子控件 (设置frame并且把上下左右的边距也设置出来)
        emoticonBtn.frame = contentView.bounds.insetBy(dx: 4, dy: 4)
    }
    
    //MARK: -- 懒加载
    
    private lazy var emoticonBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.white
        btn.isUserInteractionEnabled = false
        
        return btn
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

















